#!/usr/bin/env python
# -*- coding:utf8 -*-
import base64
from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad


def crypto_operation(input_bytes: bytes, key_bytes: bytes, algorithm: str = "AES",
                     cipher_mode: str = "AES/CBC/PKCS5Padding", encrypt: bool = True) -> bytes:
    if not input_bytes or not key_bytes:
        return None
    try:
        iv = b"99ef721etd7c1ub9"[:16].ljust(16, b'\0')

        if "CBC" in cipher_mode:
            cipher = AES.new(key_bytes, AES.MODE_CBC, iv)
        elif "ECB" in cipher_mode:
            cipher = AES.new(key_bytes, AES.MODE_ECB)
        else:
            raise ValueError("Unsupported cipher mode")

        if encrypt:
            if "PKCS5" in cipher_mode or "PKCS7" in cipher_mode:
                input_bytes = pad(input_bytes, AES.block_size)
            return cipher.encrypt(input_bytes)
        else:
            decrypted = cipher.decrypt(input_bytes)
            if "PKCS5" in cipher_mode or "PKCS7" in cipher_mode:
                return unpad(decrypted, AES.block_size)
            return decrypted

    except Exception as e:
        print(f"Crypto operation failed: {e}")
        return None


def encrypt_password(pwd: str):
    bArr = pwd.encode('utf-8')
    bArr2 = "E2A469336577149y".encode('utf-8')
    data = crypto_operation(bArr, bArr2, "AES", "AES/CBC/PKCS5Padding", True)
    result = base64.b64encode(data).decode('utf-8')
    return result
